package com.lxx.wiki.service;

import com.lxx.wiki.domain.entity.LoginUser;
import com.lxx.wiki.domain.req.UserLoginReq;
import com.lxx.wiki.domain.resp.CommonResp;
import com.lxx.wiki.domain.resp.LoginResp;
import com.lxx.wiki.utils.BeanCopyUtils;
import com.lxx.wiki.utils.JwtUtil;
import com.lxx.wiki.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;
    public CommonResp login(UserLoginReq req) {
        //AuthenticationManager authenticate进行用户验证
        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(req.getLoginName(), req.getPassword());
        try {
            Authentication authenticate = authenticationManager.authenticate(authentication);
            if (authenticate.isAuthenticated()) {
                //如果认证通过了，使用userid生成一个jwt jwt存入ResponseResult返回
                LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
                String userId = loginUser.getUser().getId().toString();
                String jwt = JwtUtil.createJWT(userId);

                //把完整的用户信息存入redis  userid作为key
                redisUtil.set("login:" + userId, loginUser);

                //把用户信息和token响应给前端
                LoginResp loginResp = BeanCopyUtils.copyBean(loginUser.getUser(), LoginResp.class);
                loginResp.setToken(jwt);

                CommonResp<LoginResp> commonResp = new CommonResp<>();
                commonResp.setContent(loginResp);

                return commonResp;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        CommonResp commonResp = new CommonResp();
        commonResp.setMessage("登录失败");
        return commonResp;
    }

    public CommonResp logout() {
        // 获取SecurityContextHolder中得用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userid = loginUser.getUser().getId();
        // 删除redis中的值
        redisUtil.del("login:" + userid);
        // 清空安全上下文
        SecurityContextHolder.clearContext();
        // 返回
        CommonResp commonResp = new CommonResp();
        commonResp.setMessage("退出成功");
        return commonResp;
    }
}
